package com.java.hohenheim.springplatform.web.security.authorize;

import com.java.hohenheim.springplatform.define.ResultCodes;
import com.java.hohenheim.springplatform.web.jwt.UserToken;
import com.java.hohenheim.springplatform.web.security.BaseUserAccessControlFilter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;

import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author LiaoJian, Hohenheim
 * @date 2020/8/24
 * @description 用户权限拦截检验
 */
public class UserAuthorizeFilter extends BaseUserAccessControlFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
        HttpServletRequest req = (HttpServletRequest) request;
        if (req.getMethod().equals(HttpMethod.OPTIONS.toString())) {
            //如果是跨域预请求，就通过该次认证
            return true;
        }

        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        boolean allow = false;
        Subject subject = getSubject(request, response);

        if (subject.getPrincipal() instanceof UserToken) {
            UserToken userToken = (UserToken) subject.getPrincipal();
            UserAuthorization userAuthorization = new UserAuthorization(userToken);
            try {
                subject.login(userAuthorization);
                allow = true;
            }
            catch (AuthenticationException e) {
                responseResult(ResultCodes.UNAUTHORIZED, response);
            }
        }
        else {
            responseResult(ResultCodes.TOKEN_SIGN_EXCEPTION, response);
        }

        return allow;
    }
}